package com.northpool.operator.common.algorithm;

import cn.hutool.core.util.StrUtil;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.representer.Representer;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;


public class NodeDslRepresenter extends Representer {
    static List<String> propList = new LinkedList<>();

    static {
        propList.add("ref");
        propList.add("version");
        propList.add("name");
        propList.add("description");

        propList.add("inputParameters");
        propList.add("outputParameters");

        propList.add("required");
        propList.add("type");
        propList.add("value");

        propList.add("spec");
        propList.add("runtimes");
        propList.add("apps");
        propList.add("cmd");

        propList.add("resultFile");
    }

    public NodeDslRepresenter(DumperOptions options) {
        super(options);
    }

    @Override
    protected Set<Property> getProperties(Class<?> type) {
        Set<Property> propertySet;
        propertySet = getPropertyUtils().getProperties(type);
        List<Property> propsList = new ArrayList<>(propertySet);
        propsList.sort(new BeanPropertyComparator());
        return new LinkedHashSet<>(propsList);
    }

    static class BeanPropertyComparator implements Comparator<Property> {
        public int compare(Property p1, Property p2) {
            if (propList.indexOf(p1.getName()) > propList.indexOf(p2.getName())) {
                return 1;
            } else if(propList.indexOf(p1.getName()) < propList.indexOf(p2.getName())) {
                return -1;
            } else if (StrUtil.equals(p1.getName(), p2.getName())) {
                return 0;
            } else {
                return -1;
            }
        }
    }
}